package com.yc154.vote.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${login.sessionKey:myinfo}")
    private String sessionKey;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        HttpSession session = request.getSession();
        Object userInfo = session.getAttribute(sessionKey);

        if (userInfo == null) {
            // 未登录
            String accept = request.getHeader("Accept");
            if (accept != null && accept.contains("application/json")) {
                // ajax请求
                response.setContentType("application/json;charset=utf-8");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                Map<String, Object> res = Map.of("code", 0, "msg", "请先登录系统");
                String json = new ObjectMapper().writeValueAsString(res);
                response.getWriter().write(json);
            } else {
                // 表单请求: 跳转到登录页面
                response.sendRedirect("/login.html");
            }
            return false;
        }
        return true;
    }
}